<!-- 账号管理 -->
<template>
<div class="dashboard-editor-container">
  <el-row style="background: #fff; padding: 16px;">
    <div style="display:flex;justify-content:space-between;">
        <!-- <div class="title">账号管理列表</div> -->
        <div >
          <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addClick()">添加服务器</el-button>
        </div>
      </div>
    <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
      <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
      <el-table-column label="服务器昵称" prop="Name" align="left" show-overflow-tooltip></el-table-column>
      <el-table-column label="服务器地址" show-overflow-tooltip prop="ServerIP" width="160px" align="left"></el-table-column>
      <el-table-column label="远程端口" show-overflow-tooltip prop="Port" width="160px" align="left"></el-table-column>
      <el-table-column label="登录用户名" show-overflow-tooltip prop="UserID" align="left"></el-table-column>
      <el-table-column label="登录密码" show-overflow-tooltip prop="Pwd" align="left"></el-table-column>
      <el-table-column label="准入资产" show-overflow-tooltip prop="Employee" align="left">
        <template slot-scope="{row}">
          <span>{{ row.Employee.length === 0 ? '全部资产' : row.Employee + '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="150px">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="changeClick(scope.row, scope.$index)">修改</el-button>
          <el-button size="mini" type="danger" @click="deleteClick(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-row>
  <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape=false
      :title="Action === 1 ? '添加服务器' : '修改服务器' "
      :visible.sync="dialogVisible"
      v-el-drag-dialog
      width="50%">
      <el-form label-width="120px" :model="accountForm" :rules="rules" ref="accountForm">
        <el-form-item label='服务器昵称:' prop="Name">
          <el-input v-model="accountForm.Name"  :disabled="Action !== 1" :maxlength="300"></el-input>
        </el-form-item>
        <el-form-item label='服务器地址:' prop="ServerIP">
          <el-input v-model="accountForm.ServerIP"  oninput="value=value.replace(/[^0-9.]/g,'')"  maxlength="15"></el-input>
        </el-form-item>
        <el-form-item label='远程端口:' prop="Port">
          <el-input v-model.number="accountForm.Port"  oninput="value=value.replace(/\D/g,'')" maxlength="5"></el-input>
        </el-form-item>
        <el-form-item label='登录用户名:' prop="UserID">
          <el-input v-model="accountForm.UserID"></el-input>
        </el-form-item>
        <el-form-item label='登录密码:' prop="Pwd">
          <el-input v-model="accountForm.Pwd"></el-input>
        </el-form-item>
        <el-form-item label='准入资产:' prop="Employee">
          <el-radio v-model="accountForm.radio" :label="1" @input="radioChange">允许全部资产访问</el-radio>
          <el-radio v-model="accountForm.radio" :label="2" @input="radioChange">允许指定资产访问</el-radio>
          <el-select v-model="accountForm.Employee" :disabled="accountForm.radio === 1" multiple placeholder="请选择" style="width:100%">
            <el-option
              v-for="item in assetList"
              :key="item.DeviceID"
              :label="item.DeviceName"
              :value="item.DeviceName">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
</div>
</template>

<script>
import { connrequest } from '@/api/firstPage'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
directives: { elDragDialog },
data() {
return {
  pageNum: 1,
  pageSize: 10,
  tableData: [],
  ipList: [],
  portList: [],
  assetList: [],
  shopNameList: [],
  Action: 1,
  userIndex: 0,
  dialogVisible: false,
  accountForm: {},
  options: [],
  rules: {
    Name: [
      { required: true, message: "请输入服务器昵称"}
    ],
    ServerIP: [
      { required: true, message: "请输入服务器ip地址"},
      {
        validator: function(rule, value, callback) {
          if (/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/.test(value) == false  && value) {
            callback(new Error("服务器地址格式错误，地址暂不支持英文"));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ],
    Port: [
      { required: true, message: "请输入端口"},
      {
        validator: function(rule, value, callback) {
          if (/^([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/.test(value) == false  && value) {
            callback(new Error("端口格式错误"));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ],
    UserID:[
      { required: true, message: "请输入登录用户名"}
    ],
    Pwd:[
      { required: true, message: "请输入登录密码"}
    ],
  }
}
},
//生命周期 - 创建完成（访问当前this实例）
created() {
  this.getData()
  this.CenterGetDevice()
},
//生命周期 - 挂载完成（访问DOM元素）
mounted() {

},
methods: {
  async CenterGetDevice(){
    const data = {
      Paging:{
        QueryPageNo: 1,
        QueryPageLength: 100000000
      },
      Filter:{
        Status: 0,
      }
    }
    const res = await connrequest('CenterGetDevice', data)
    this.assetList = res.Data
  },
  async getData(){
    const res = await connrequest('GetAmazonCfg')
    this.tableData = res.Data
  },
  addClick(){
    this.Action = 1
    let arr = [...this.tableData]
    let ipList = []
    let shopNameList = []
    arr.map(item => {
      ipList.push(item.ServerIP)
      shopNameList.push(item.Name)
    })
    this.ipList = ipList
    this.shopNameList = shopNameList
    this.dialogVisible = true
    this.$nextTick(()=>{
      this.accountForm = {Port: 3389, radio: 1, Employee: []}
      this.$refs['accountForm'].resetFields();
    })
  },
  changeClick(row, index){
    this.userIndex = index
    this.Action = 2
    this.$nextTick(()=>{
      this.accountForm = {...row, Employee: row.Employee }
      this.$refs['accountForm'].resetFields();
    })
    let arr = [...this.tableData]
    arr.splice(index, 1)
    let ipList = []
    let portList = []
    let shopNameList = []
    arr.map(item => {
      ipList.push(item.ServerIP)
      portList.push(item.Port * 1)
      shopNameList.push(item.Name)
    })
    this.ipList = ipList
    this.portList = portList
    this.shopNameList = shopNameList
    this.dialogVisible = true
  },
  deleteClick(row){
    this.$confirm('此操作将永久删除该服务器, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      this.tableData.map( (item, i) => {
        if(item.ServerIP === row.ServerIP){
          this.tableData.splice(i, 1)
        }
      })
      let data = {
        Data:[
          ...this.tableData,
        ]
      }
      const res = await connrequest('SetAmazonCfg', data)
      if(res.Status.StatusCode === 0){
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.getData()
        this.dialogVisible = false
      }
    }).catch(() => {
      this.$message({
        type: 'info',
        message: '已取消删除'
      });          
    });
  },
  radioChange(value){
    this.$set(this.accountForm, 'Employee', [])
  },
  submit(){
    this.$refs['accountForm'].validate( async(valid) => {
      if(valid){
        if(this.shopNameList.indexOf(this.accountForm.Name) !== -1){
          this.$message.error('该服务器昵称已经存在')
          return false
        }else if(this.ipList.indexOf(this.accountForm.ServerIP) !== -1){
          this.$message.error('该服务器地址已经存在')
          return false
        }else if((this.ipList.indexOf(this.accountForm.ServerIP) !== -1 && this.portList.indexOf(this.accountForm.Port * 1) !== -1)){
          this.$message.error('该端口已经存在')
          return false
        }else if(this.accountForm.Port === 10808){
          this.$message.error('不可使用系统内置端口')
          return false
        }else if(this.accountForm.radio === 2 && this.accountForm.Employee.length === 0){
          this.$message.error('指定资产不能为空')
          return false
        }else{
          if(this.Action === 1){
            this.accountForm.Employee = this.accountForm.Employee || []
            this.tableData.push(this.accountForm)
          }else if(this.Action === 2){
            this.tableData[this.userIndex] = this.accountForm
          }
          let data = {
            Data:[
              ...this.tableData,
            ]
          }
          const res = await connrequest('SetAmazonCfg', data)
          if(res.Status.StatusCode === 0){
            this.getData()
            this.dialogVisible = false
          }
        }
      }
    })
  },
}
}
</script>
<style scoped>
/* @import url(); 引入css类 */
.el-dialog__title::before {
  padding-left: 30px; /* 调整标题和图标的距离 */
  background-image: url('../../assets/logo.png'); /* 指定图标路径 */
  background-repeat: no-repeat; /* 防止背景图片重复 */
  background-position: left center; /* 将图标放在标题左侧中间 */
}

</style>